package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.PaymentTypeMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentTypeMapper paymentTypeMapper;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public void savePaymentInfo(OrderInfo orderInfo, String paymentType) {

        // 在进入方法的时候先根据支付类型和订单id查询是否有这条记录，如果有直接返回
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("order_id", orderInfo.getId());
        paymentInfoQueryWrapper.eq("payment_type", paymentType);

        Integer integer = paymentTypeMapper.selectCount(paymentInfoQueryWrapper);
        if (integer > 0) return;

        // 保存交易信息
        if (orderInfo != null){
            // 转换数据
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setCreateTime(new Date());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(paymentType);
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
            paymentInfo.setSubject(orderInfo.getTradeBody());
            //paymentInfo.setSubject("test");
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            // 添加交易记录
            paymentTypeMapper.insert(paymentInfo);
        }
    }

    /**
     * 修改交易记录状态
     * @param out_trade_no
     * @param name
     * @param paramsMap
     */
    @Override
    public void updatePayMentInfo(String out_trade_no, String name, Map<String, String> paramsMap) {

        // 修改订单得状态
        PaymentInfo paymentInfo = this.getPaymentInfo(out_trade_no, name);

        if (paymentInfo != null){
            paymentInfo.setCallbackTime(new Date());
            paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
            paymentInfo.setCallbackContent(paramsMap.toString());
            paymentInfo.setTradeNo(paramsMap.get("trade_no"));

            paymentTypeMapper.updateById(paymentInfo);

            // 使用mq发送消息，修改orderinfo订单状态
            this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,MqConst.ROUTING_PAYMENT_PAY,paymentInfo.getOrderId());
        }else{
            return;
        }

    }

    /**
     * 根据订单编号和支付方式获取订单得数据
     * @param out_trade_no 订单编号
     * @param name 支付方式
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(String out_trade_no, String name) {

        // 设置条件
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("out_trade_no",out_trade_no);
        paymentInfoQueryWrapper.eq("payment_type",name);

        PaymentInfo paymentInfo = paymentTypeMapper.selectOne(paymentInfoQueryWrapper);

        return paymentInfo;
    }

    @Override
    public boolean refund(Long orderId) {

        // 根据orderId 查询订单
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = paymentTypeMapper.selectOne(paymentInfoQueryWrapper);


        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", paymentInfo.getTradeNo());
        bizContent.put("refund_amount", "0.01");
        bizContent.put("out_request_no", "HZ01RF001");

        //// 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){

            System.out.println("调用成功");
            // 修改订单状态
            this.updatePayMentClose(paymentInfo.getOutTradeNo(),paymentInfo.getPaymentType());
            return true;
        } else {

            System.out.println("调用失败");
            return false;
        }


    }

    /**
     * 退款成功修改状态
     * @param outTradeNo
     * @param paymentType
     */
    private void updatePayMentClose(String outTradeNo, String paymentType) {

        PaymentInfo paymentInfo = this.getPaymentInfo(outTradeNo, paymentType);
        paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());

        paymentTypeMapper.updateById(paymentInfo);

    }
}
